import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Dormitory, DormitoryQuery, DormitoryResponse, DormitoryType } from '../types/dormitory';

@Injectable({
  providedIn: 'root'
})
export class DormitoryService {
  private baseUrl = 'http://localhost:8080/dormitories';

  constructor(private http: HttpClient) {}

  getDormitories(query?: DormitoryQuery): Observable<DormitoryResponse<DormitoryType>> {
    let params = new HttpParams();
    if (query) {
      if (query.page) params = params.set('page', query.page.toString());
      if (query.page_size) params = params.set('page_size', query.page_size.toString());
      if (query.building) params = params.set('building', query.building);
    }
    return this.http.get<DormitoryResponse<DormitoryType>>(this.baseUrl, { params });
  }

  getDormitory(id: number): Observable<Dormitory> {
    return this.http.get<Dormitory>(`${this.baseUrl}/${id}`);
  }

  createDormitory(dormitory: Dormitory): Observable<Dormitory> {
    return this.http.post<Dormitory>(this.baseUrl, dormitory);
  }

  updateDormitory(id: number, dormitory: Dormitory): Observable<Dormitory> {
    return this.http.put<Dormitory>(`${this.baseUrl}/${id}`, dormitory);
  }

  deleteDormitory(id: number): Observable<void> {
    return this.http.delete<void>(`${this.baseUrl}/${id}`);
  }
}